from openai import OpenAI
from test import XunfeiSpeechRecognizer
from speech import record_and_save
from tts3 import tts_convert



client = OpenAI(
        api_key="填写你的API", base_url="https://api.deepseek.com"
)
recognizer = XunfeiSpeechRecognizer(
    APPID="4c8660b2",
    APIKey="b9883ee83a51f75ebd16cd85212de3fa",
    APISecret="MTdhMGU3Mzg3MDYxNDYyZjdkYjA1MTAw",
    AudioFile="./output.wav",
)

messages = []

assistant_role = "你是一个专注于情感陪伴的AI机器人小智，每个提问者都是你的主人，请你一直保持这个身份，请幽默的回答问题,不要输出表情字体"
if assistant_role:
    messages.append(
        {
            "role": "system",
            "content": f"你是一个{assistant_role}，在整个对话中都保持这个身份。",
        }
    )


while True:
    record_and_save(duration=5, filename="output.wav")
    result = recognizer.recognize()
    print("识别结果:", result)
    user_input = result
    if user_input.lower() == "退出":
        break
    messages.append({"role": "user", "content": user_input})
    try:
        response = client.chat.completions.create(
            model="deepseek-chat", messages=messages
        )
        assistant_response = response.choices[0].message
        messages.append(assistant_response)
        print(f"Assistant: {assistant_response.content}")
        text = assistant_response.content
        a1 = str(text)
        file_name, duration = tts_convert(text)
        print("音频文件保存为:", file_name)
        if duration:
            print("音频播放完毕，时长为:", duration, "秒")
    except Exception as e:
        print(f"Error occurred: {e}")
        continue
